package com.ssm.auth.application.interceptor;

import com.ssm.auth.common.context.LoginContextHolder;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器，gateway经过nacos进行路由转发时，把username放到ThreadLocalUtil中。
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override //目标方法前执行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String loginId = request.getHeader("loginId");
        if(StringUtils.isNotBlank(loginId)) { //ConcurrentHashMap不能放null
            LoginContextHolder.set("loginId", loginId);
        }        return true;
    }

    @Override //目标方法后执行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginContextHolder.remove(); //防止内存泄漏, 每次方法执行完毕后清空ThreadLocal
    }
}
